#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "sync.h"

Sync::Sync() {
	lastframe = t0 = ticks();
	srand(time());
}

Sync::~Sync() {
}

void
Sync::channel(const int id, float value) {
	channels[id] = value;
}

float
Sync::channel(const int id) {
	std::map<int,float>::iterator it = channels.find(id);
	if (it == channels.end()) {
		return 0;
	}
	return (*it).second;
}

void Sync::timeStart() {
	t0 = ticks();
}

float Sync::framestart() {
	long int now = ticks();
	long int diff = now - lastframe;
	lastframe = now;
	adjustedTime = ((float)(now - t0)) / NANOTIME;

	this->channel(SYNC_SINE, 0.5 + 0.5*sin(adjustedTime));
	this->channel(SYNC_SINE_FAST, 0.5 + 0.5 * sin(adjustedTime * 10));
	this->channel(SYNC_RANDOM, rand() > RAND_MAX*0.75 ? 1 : 0);

	float dt = ((float)diff) / NANOTIME;
	adjustedFps = 1 / dt;
	return dt;
}

float Sync::time() {
	return adjustedTime;
}

float Sync::fps() {
	return adjustedFps;
}

long int Sync::ticks() {
	timespec ts;
	clock_gettime(0, &ts);
	return ts.tv_sec* 1000000000 + ts.tv_nsec;
}
